package lib.control;

import java.util.List;

import lib.api.IMDB.IMDBAPI;
import lib.api.IMDB.IMDBException;
import lib.api.IMDB.IMDBSearchID;
import lib.api.IMDB.model.IMDBDetails;
import lib.exception.VideoControlException;
import lib.logging.Logger;
import lib.model.MovieFile;
import lib.model.VideoFile;
import settings.model.MappingBierdopjeScene;

public class MovieFileControl extends VideoFileControl {
	private final IMDBSearchID imdbSearchID;
	private final IMDBAPI imdbapi;

	public MovieFileControl(MovieFile movieFile) {
		super(movieFile);
		imdbapi = new IMDBAPI();
		imdbSearchID = new IMDBSearchID();
	}

	@Override
	public VideoFile process(List<MappingBierdopjeScene> dict)
			throws VideoControlException {
		Logger.instance.trace("MovieFileControl", "process", "");
		MovieFile movieFile = (MovieFile) videoFile;
		if (movieFile.getTitle().equals("")) {
			throw new VideoControlException(
					"Unable to extract/find title, check file", videoFile);
		} else {
			int imdbid;
			imdbid = imdbSearchID.getImdbId(movieFile.getTitle(),
					movieFile.getYear());
			if (imdbid > 0) {
				movieFile.setImdbid(imdbid);
				IMDBDetails imdbinfo;
				try {
					imdbinfo = imdbapi.getIMDBMovieDetails(movieFile
							.getImdbidAsString());
					if (imdbinfo != null) {
						movieFile.setYear(imdbinfo.getYear());
						movieFile.setTitle(imdbinfo.getTitle());
					} else {
						Logger.instance
								.error("Unable to get details from IMDB API, continue with filename info"
										+ videoFile);
					}
				} catch (IMDBException e) {
					throw new VideoControlException(
							"IMDBAPI Failed", videoFile);
				}

			} else {
				throw new VideoControlException(
						"Movie not found on IMDB, check file", videoFile);
			}
			return movieFile;
		}
	}

	@Override
	public VideoFile processWithSubtitles(List<MappingBierdopjeScene> dict,
			String languageCode, boolean exactMatch)
			throws VideoControlException{
		Logger.instance.trace("MovieFileControl", "processWithSubtitles", "");
		MovieFile movieFile = (MovieFile) process(dict);
		movieFile.setMatchingSubs(sc.getSubtitles(movieFile, exactMatch,
				languageCode));
		return movieFile;
	}

}
